<template>
  <div style="position: absolute; top: 0">
    <input id="uploadBtn" type="file" @change="loadExcel" />

    <button @click="setDataType(0)">设置表头</button>
    <button @click="setDataType(1)">设置数据</button>
    <button @click="downloadExcel">保存</button>
  </div>
  <div id="luckysheet"></div>
  <div v-show="isMaskShow" id="tip">Downloading</div>
</template>

<script setup>
import { ref, onMounted, reactive, unref } from "vue";
import { exportExcel } from "./export";
import LuckyExcel from "luckyexcel";
import FileSaver from "file-saver";

const isMaskShow = ref(false);
const fileName = ref("");
const colors = ["#ff00ff", "#00ff00"];
let sheetsData = null;
// 最终返回数据
const result = {
  sheets: [],
};
// 当前选中数据
const seletedData = reactive({});
const jsonData = ref({});

const setDataType = (type) => {
  // let sheetOrder = result.sheets[seletedData.sheet];
  seletedData.rows.forEach(v => {
    sheetsData[seletedData.sheet][v] = type
  })
  // sheetsData[seletedData.sheet].forEach((v, i) => {

  //   seletedData.rows.includes(i);
  //   sheetsData[seletedData.sheet][i] = type;
  //   console.log(sheetsData[seletedData.sheet])
  // });



  setColors(type);

  // sheetOrder[type ? "data" : "headers"] = sheetOrder[type ? "data" : "headers"]
  //   .concat(unref(seletedData.rows))
  //   .sort((a, b) => a - b);
};

const setColors = (type) => {
  luckysheet.menuButton.updateFormat(null, "bg", colors[type]);
};

const loadExcel = (evt) => {
  const files = evt.target.files;
  if (files == null || files.length == 0) {
    alert("No files wait for import");
    return;
  }

  let name = files[0].name;
  let suffixArr = name.split("."),
    suffix = suffixArr[suffixArr.length - 1];
  fileName.value = suffixArr[0];
  // if (suffix != "xlsx") {
  //   alert("Currently only supports the import of xlsx files");
  //   return;
  // }
  LuckyExcel.transformExcelToLucky(
    files[0],
    function (exportJson, luckysheetfile) {
      if (exportJson.sheets == null || exportJson.sheets.length == 0) {
        alert(
          "Failed to read the content of the excel file, currently does not support xls files!"
        );
        return;
      }
      console.log("exportJson", exportJson);
      // 初始化 sheets 长度
      result.sheets = Array.from({ length: exportJson.sheets.length }).map(
        (v) => {
          return { data: [], headers: [] };
        }
      );

      console.log(result, "-====");
      jsonData.value = exportJson;

      window.luckysheet.destroy();

      window.luckysheet.create({
        container: "luckysheet", //luckysheet is the container id
        showinfobar: false,
        data: exportJson.sheets,
        title: exportJson.info.name,
        userInfo: exportJson.info.name.creator,
        hook: {
          sheetMouseup: (c, p, sheet, { rowsSelectedStatus }) => {
            if (rowsSelectedStatus) {
              const sRow = sheet.luckysheet_select_save.filter(
                (v) => v?.row_select
              );
              const rowNums = [];

              sRow.forEach((v) => {
                if (v.row[0] === v.row[1]) {
                  rowNums.push(v.row[0]);
                } else {
                  for (let i = v.row[0]; i <= v.row[1]; i++) {
                    rowNums.push(i);
                  }
                }
              });
              rowNums.sort((a, b) => a - b);

              Object.assign(seletedData, {
                sheet: sheet.order,
                rows: rowNums,
              });

              console.log(seletedData, "--");
            }
          },
          workbookCreateAfter: (options) => {
            console.log(options);
            // sheet
            sheetsData = Array.from({ length: options.data.length })
            .map(
              (item, i) => {
                return Array.from({ length: options.data[i].data.length }).fill(undefined);
              }
            );
          },
        },
      });
    }
  );
};
const downloadExcel = () => {


  console.log('result', result)
  console.log('sheetsData', sheetsData)


  result.sheets.forEach((item, sidx) => {
    for (const key in sheetsData[sidx]) {
      if (sheetsData[sidx][key] === 1) {
        item.data.push(key)
      } else if (sheetsData[sidx][key] === 0) {
        item.headers.push(key)
      }
    }
  });
  const blob = new Blob([JSON.stringify(unref(result), null, 2)], {
    type: "application/json",
  });

  FileSaver.saveAs(blob, fileName.value + ".json");
  // exportExcel(luckysheet.getAllSheets(), "下载");
};

// !!! create luckysheet after mounted
onMounted(() => {
  luckysheet.create({
    container: "luckysheet",
  });
});
</script>

<style scoped>
#luckysheet {
  margin: 0px;
  padding: 0px;
  position: absolute;
  width: 100%;
  left: 0px;
  top: 30px;
  bottom: 0px;
}

#uploadBtn {
  font-size: 16px;
}

#tip {
  position: absolute;
  z-index: 1000000;
  left: 0px;
  top: 0px;
  bottom: 0px;
  right: 0px;
  background: rgba(255, 255, 255, 0.8);
  text-align: center;
  font-size: 40px;
  align-items: center;
  justify-content: center;
  display: flex;
}
</style>
